package com.itheima.thread.等待唤醒机制.快递员案例;

public class Demo {
    public static void main(String[] args) {
        Box box = new Box();
        //创建对象并启动
        new Thread(() -> {
            int count = 0;
            while (true){

                System.out.println("快递员在行动......");
                synchronized ("abc"){
                    if (box.getCount()==0){
                        System.out.println("送完下班");
                        break;
                    }else {
                        if (box.isFlag()){
                            System.out.println("快递柜占用,等待取货");
                            try {
                                "abc".wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }else {
                            System.out.println("将第" + ++count + "个快递放入快递柜,通知收件人取货");
                            "abc".notify();
                            box.setFlag(true);
                        }
                    }
                }
            }
        }).start();
        new Thread(() ->{
            int count = 0;
            while (true){
                System.out.println("菜鸟驿站在行动......");
                synchronized ("abc"){
                    if (box.getCount()==0){
                        System.out.println("取完关门");
                        break;
                    }else {
                        if (box.isFlag()){
                            System.out.println("收件人取走了第" + ++count + "个快递,通知快递员发件");
                            box.setFlag(false);
                            box.countSubtract();
                            "abc".notify();
                        }else {
                            System.out.println("等待快递员发件");
                            try {
                                "abc".wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }).start();
    }
}
